package com.xuesinuo.ots.api;

import java.io.File;
import java.io.IOException;
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import com.xuesinuo.ots.config.auth.Auth;
import com.xuesinuo.ots.config.spring.ApiResultPacking;
import com.xuesinuo.ots.util.FileUtil;
import com.xuesinuo.ots.util.IdUtil;
import com.xuesinuo.ots.util.StringUtil;

import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.RequiredArgsConstructor;

/** 文件 */
@RestController
@RequestMapping("/backend/file")
@ApiResultPacking
@RequiredArgsConstructor
public class FileApi {

    @Value("${file.upload-path:./upload}")
    private String uploadPath;
    @Value("${file.upload-url:/upload}")
    private String uploadUrl;

    private String getUploadPath() {
        String path = uploadPath;
        String last = path.substring(path.length() - 1);
        if (!last.equals("/")) {
            path += "/";
        }
        return path;
    }

    private String getUploadUrl() {
        String path = uploadUrl;
        String last = path.substring(path.length() - 1);
        if (!last.equals("/")) {
            path += "/";
        }
        return path;
    }

    @Data
    @AllArgsConstructor
    public static class UploadResult {
        private String path;
    }

    /** 上传，随机文件名 */
    @Auth("File:Upload")
    @PostMapping("/upload")
    public UploadResult upload(@RequestParam("file") MultipartFile file) throws IOException {
        String uuid = IdUtil.getUUID();
        String date = LocalDate.now().format(DateTimeFormatter.ofPattern("yyyyMMdd")) + "/";
        String fileName = file.getResource().getFilename();
        if (fileName == null) {
            fileName = uuid;
        } else {
            fileName = fileName.replaceAll(",", "");
        }
        String suffixName = FileUtil.getSuffix(fileName);
        if (StringUtil.isNotBlank(suffixName)) {
            suffixName = "." + suffixName;
        }
        File localFile = FileUtil.createFileWithParentDirs(this.getUploadPath() + date + uuid + suffixName);
        FileUtil.writeFromInputStreamAndClose(file.getInputStream(), localFile);
        return new UploadResult(this.getUploadUrl() + date + uuid + suffixName);
    }

    /** 保有原文件名，上传（每个文件单独分配一个目录，以区分相同文件名） */
    @Auth("File:Upload")
    @PostMapping("/uploadWithFileName")
    public UploadResult uploadWithFileName(@RequestParam("file") MultipartFile file) throws IOException {
        String uuid = IdUtil.getUUID();
        String date = LocalDate.now().format(DateTimeFormatter.ofPattern("yyyyMMdd")) + "/";
        String fileName = file.getResource().getFilename();
        if (fileName == null) {
            fileName = uuid;
        } else {
            fileName = fileName.replaceAll(",", "");
        }
        File localFile = FileUtil.createFileWithParentDirs(this.getUploadPath() + date + uuid + "/" + fileName);
        FileUtil.writeFromInputStreamAndClose(file.getInputStream(), localFile);
        return new UploadResult(this.getUploadUrl() + date + uuid + "/" + fileName);
    }
}
